﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class EmailGame : MonoBehaviour {

    public GameObject photoCamera;
    public GameObject returnHomeBtn;
    public GameObject retuanMainBtn;
    public GameObject[] photos;
    public GameObject photo;
    public int emailNum = 0;
    public int getEmailNum = 0;

    private GameObject ledi;
    public GameObject getPhoto;
    public GameObject effect;
    public GameObject getPhoto_plane;
    private bool sendPhotoFinish = false;
    public GameObject plane;
    public GameObject canvas;
    public GameObject mainCam;
    public GameObject book;


    private const string uiPath = "game_puzzle/game_puzzle_materials/";

    private int EmailGameTime=0;

    public GameObject finger;

    private float time;

    public GameObject flower;

    public GameObject flowerEffect;

    public GameObject photoEffect;

    private float length;

    private bool isInPhotos =false;

    public static EmailGame instance;

    private Vector3 getPhotoPos;
    private Vector3 getPhotoScale;
    private Quaternion getPhotoRotation;

    private GameObject LediHead;

    private bool changePhoto =false;

    private const string bgPath = "sound_bg/";

    public int GetEmailNum
    {
        get
        {
            return getEmailNum;
        }
    }

    public int OldPhotoNum
    {
        get
        {
            return (getEmailNum-1) % 12;
        }
    }


    // Use this for initialization
    void Awake()
    {
        instance = this;
    }

    // Use this for initialization
    void Start()
    {
        Input.multiTouchEnabled = false;
        finger.SetActive(false);
        sendPhotoFinish = false;

        getPhotoPos = getPhoto.transform.position;
        getPhotoScale = getPhoto.transform.localScale;
        getPhotoRotation = getPhoto.transform.rotation;
        ledi = Instantiate(ResourceManager.Instance.GetResource("model/model_actor/ledi", typeof(GameObject), enResourceType.Prefab, false).m_content as GameObject, new Vector3(65, 0, 29),Quaternion.Euler(0,-30,0));

        object Controller = ResourceManager.Instance.GetResource("Controller/lediController_idel_p", typeof(object), enResourceType.Prefab, false).m_content as object;
        ledi.transform.Find("101001000@skin").GetComponent<Animator>().runtimeAnimatorController = (RuntimeAnimatorController)Controller;
        Destroy(ledi.transform.GetComponent<HeroInputEvent>());
        LediHead = ledi.transform.Find("101001000@skin/101001000_head").gameObject;
        AudioManager.Instance.PlaySound(Itempathinfo.puzzleGamePath + "404030101");
  
            ledi.transform.Find("101001000@skin").GetComponent<Animator>().Play("all_talk_01");
            length = AudioManager.Instance.GetAudioClip(Itempathinfo.puzzleGamePath + "404030101").length;
            StartCoroutine(LediTalkFinish());
        
        GetInfo();
        AudioManager.Instance.PlayMusic(bgPath + "604030101", true, true);





        if (PlayerPrefs.GetString(PlayerPrefabInfo.jsonData) != "") 
        {
            string result = PlayerPrefs.GetString(PlayerPrefabInfo.jsonData);
            PhotoDataList tlData = new PhotoDataList();
            tlData = JsonUtility.FromJson<PhotoDataList>(result);

            for (int i = 0; i < photos.Length; i++)
            {

                Material a = ResourceManager.Instance.GetResource(uiPath + tlData.photoDataList[i].meterialName, typeof(Material), enResourceType.Prefab, false, false).m_content as Material;
                photos[i].GetComponent<MeshRenderer>().material = a;
                //Debug.Log(a);
                photos[i].transform.position = tlData.photoDataList[i].pos;
                photos[i].gameObject.SetActive(tlData.photoDataList[i].isShow);
            }
        }
    }


    IEnumerator LediTalkFinish() {
        yield return new WaitForSeconds(length);
        ledi.transform.Find("101001000@skin").GetComponent<Animator>().SetTrigger("all_tlak");
        
        
    }


    public void Showledi(bool isActive) {
        ledi.SetActive(isActive);
        LediHead.GetComponent<SkinnedMeshRenderer>().SetBlendShapeWeight(4, 24);
        LediHead.GetComponent<SkinnedMeshRenderer>().SetBlendShapeWeight(12, 0);
    }





    // Update is called once per frame
    void Update () {
        time += Time.deltaTime;
        if(time>=20&&isInPhotos ==false) {
           int num = Random.Range(1, 3);
            if (num == 1)
            {
               
                AudioManager.Instance.PlaySound(Itempathinfo.puzzleGamePath + "404030102");
                ledi.transform.Find("101001000@skin").GetComponent<Animator>().Play("all_talk_01");
                length = AudioManager.Instance.GetAudioClip(Itempathinfo.puzzleGamePath + "404030102").length;
                StartCoroutine(LediTalkFinish());
            }
            else {
              
                AudioManager.Instance.PlaySound(Itempathinfo.SOUND + "401010144");
                ledi.transform.Find("101001000@skin").GetComponent<Animator>().Play("all_talk_01");
                length = AudioManager.Instance.GetAudioClip(Itempathinfo.SOUND + "401010144").length;
                StartCoroutine(LediTalkFinish());
            }
            time = 0;
        }
		
	}

    public void CloseBook() {
        book.SetActive(false);
    }

    public void SetPlane(bool a) {
        plane.SetActive(a);
    }

    public void ClearTime() {
        time = 0;
    }

    public void SetPhotoCamera() {
        
        photoCamera.SetActive(true);
        returnHomeBtn.SetActive(true);
        SetPhotoClick();
    }



    public void HideLedi() {
        ledi.SetActive(false);
    }

    public void ClosePhotoCamera() {
        book.SetActive(true);
        time = 0;
        isInPhotos = false;
        photoCamera.SetActive(false);
        returnHomeBtn.SetActive(false);
        SetPhotoData();
        ledi.SetActive(true);
        retuanMainBtn.SetActive(true);
        PhotoInput.DoEvent();
        foreach(var temp in photos){
            temp.GetComponent<MeshCollider>().enabled = false;
        }
   }


    public void SetPhotoClick()
    {
        foreach (var temp in photos)
        {
            temp.GetComponent<PhotoInput>().enabled = true;
            temp.GetComponent<MeshCollider>().enabled = true;
;        }
    }

    public void RemovePhotoClick() {
        foreach (var temp in photos)
        {
            temp.GetComponent<PhotoInput>().enabled = false;
        }
    }

    private void ShowPhoto() {
        int num = Random.Range(1, 11);
        Material a = ResourceManager.Instance.GetResource(uiPath + "sd_mxp" + num.ToString(), typeof(Material), enResourceType.Prefab, false, false).m_content as Material;
        getPhoto_plane.GetComponent<MeshRenderer>().material = a;
        effect.SetActive(true);
        Invoke("ShowThisPhoto", 3f);
        

        
    }

    public void PhotoMove() {
        
        Debug.Log(getEmailNum);
        getPhoto.transform.DOMove(photos[getEmailNum-1].transform.position,1f).OnComplete(ShowAllPhoto);
        getPhoto.transform.DOScale(new Vector3(4, 2.2f, 2.2f), 1f);
        
        //photoEffect.SetActive(true);
        //photoEffect.transform.position = photos[getEmailNum - 1].transform.position;

    }

    void ShowAllPhoto() {
        sendPhotoFinish = true;
        
        photos[getEmailNum - 1].SetActive(true);
        photos[getEmailNum - 1].GetComponent<MeshRenderer>().material = getPhoto_plane.GetComponent<MeshRenderer>().material;

        
        getPhoto.SetActive(false);
        Destroy(getPhoto.GetComponent<HeroInputEvent>());
        
        SetPhotoData();



    }

    public void SetPhotoData() {
        PhotoDataList ph = new PhotoDataList();
        
        foreach(Transform child in photo.transform) {
            PhotoData data = new PhotoData();
            data.meterialName = child.GetComponent<MeshRenderer>().material.name.Replace(" (Instance)",string.Empty);
            data.pos = child.transform.position;
            data.isShow = child.gameObject.activeSelf;
            //Debug.Log(data.pos);
            ph.photoDataList.Add(data);

        }

        string jsonData = JsonUtility.ToJson(ph);

        //Debug.Log(jsonData);

        PlayerPrefs.SetString(PlayerPrefabInfo.jsonData, jsonData);
        if (sendPhotoFinish||changePhoto)
        {
            PlayerPrefs.SetInt(PlayerPrefabInfo.sendEmailNum, emailNum);
            PlayerPrefs.SetInt(PlayerPrefabInfo.getEmailNum, getEmailNum);
        }

    }

    public void ReturnToMain() {
        Input.multiTouchEnabled = true;
        GameStateManager.Instance.GotoState(GameStateName.MAIN_STATE);
        //AudioManager.Instance.StopAllSound();
        SetPhotoData();
        PhotoInput.DoEvent();
        retuanMainBtn.SetActive(false);
        ChangePhotoController.Instance.CloseView();



    }

    public void CloseMainBtn() {
        
        retuanMainBtn.SetActive(false);
    }

    private void ShowThisPhoto() {
        getPhoto.SetActive(true);
        effect.SetActive(false);
        mainCam.GetComponent<InputPhysicsRaycaster>().enabled = true;
        
    }


    public void GetInfo() {
        sendPhotoFinish = false;
        changePhoto = false;
    
        ledi.SetActive(true);

        if (!getPhoto.GetComponent<HeroInputEvent>())
        {
            getPhoto.AddComponent<HeroInputEvent>();
        }
        finger.SetActive(false);
        //Camera.main.GetComponent<InputPhysicsRaycaster>().enabled = true;
        photoEffect.SetActive(false);
        getPhoto.SetActive(false);
        getPhoto.transform.rotation = getPhotoRotation;
        getPhoto.transform.localScale = getPhotoScale;
        getPhoto.transform.position = getPhotoPos;
        flowerEffect.SetActive(false);
        if (PlayerPrefs.GetInt(PlayerPrefabInfo.EmailGametime)==0) {
            EmailGameTime++;
            finger.SetActive(true);
            PlayerPrefs.SetInt(PlayerPrefabInfo.EmailGametime, EmailGameTime);
        }
       
        if (PlayerPrefs.GetInt(PlayerPrefabInfo.sendEmailNum) != 0)
        {
            AudioManager.Instance.StopAllSound();
            Camera.main.GetComponent<InputPhysicsRaycaster>().enabled = false;
            emailNum = PlayerPrefs.GetInt(PlayerPrefabInfo.sendEmailNum);
            
            emailNum--;
            
            time = 0;
           
            int num = Random.Range(1, 6);
            if (num == 5)
            {
                
                Debug.Log("aaaaaaaaaaaaaaaaaaaaaaaa");
                AudioManager.Instance.StopAllSound();
                AudioManager.Instance.PlaySound(Itempathinfo.puzzleGamePath + "404030501");
                ledi.transform.Find("101001000@skin").GetComponent<Animator>().Play("all_talk_01");
                length = AudioManager.Instance.GetAudioClip(Itempathinfo.puzzleGamePath + "404030501").length;
                StartCoroutine(LediTalkFinish());
                ShowFlower();
            }
            else
            {
                getEmailNum = PlayerPrefs.GetInt(PlayerPrefabInfo.getEmailNum);
                getEmailNum++;
                AudioManager.Instance.StopAllSound();
                AudioManager.Instance.PlaySound(Itempathinfo.puzzleGamePath + "404030401");
                ledi.transform.Find("101001000@skin").GetComponent<Animator>().Play("all_talk_01");
                length = AudioManager.Instance.GetAudioClip(Itempathinfo.puzzleGamePath + "404030401").length;
                StartCoroutine(LediTalkFinish());
                ShowPhoto();
            }
            
            

        }
       
    }

    private void ShowFlower() {
        flower.SetActive(true);
        mainCam.GetComponent<InputPhysicsRaycaster>().enabled = true;

    }

    public void ShowFlowerEffect() {
        StopAllCoroutines();
        PlayerPrefs.SetInt(PlayerPrefabInfo.sendEmailNum, emailNum);
        AudioManager.Instance.PlaySound(Itempathinfo.puzzleGamePath + "604030304");
        AudioManager.Instance.PlaySound(Itempathinfo.puzzleGamePath + "404030501");
        ledi.transform.Find("101001000@skin").GetComponent<Animator>().Play("all_talk_01");
        length = AudioManager.Instance.GetAudioClip(Itempathinfo.puzzleGamePath + "404030501").length;
        StartCoroutine(LediTalkFinish());
        flowerEffect.SetActive(true);
    }

    

    public void SetIsInPhotos() {
        isInPhotos = true;
    }


    public void SetButton(bool isActive) {
        retuanMainBtn.SetActive(isActive);
    }

    public void SetCamEvent() {
        mainCam.GetComponent<InputPhysicsRaycaster>().enabled = true;
        ledi.SetActive(true);
    }

    public string GetLastPhotoName() {
        string name = getPhoto_plane.GetComponent<MeshRenderer>().material.name.Replace(" (Instance)", string.Empty);
         return name;
    }

    public string GetFirstPhotoName() {
        string name = photos[OldPhotoNum].GetComponent<MeshRenderer>().material.name.Replace(" (Instance)", string.Empty);
        return name;
    }

    public void ChangePhoto() {
        changePhoto = true;
         photos[OldPhotoNum].GetComponent<MeshRenderer>().material = getPhoto_plane.GetComponent<MeshRenderer>().material;
        photoEffect.transform.position = photos[OldPhotoNum].transform.position;
        photoEffect.SetActive(true);
        PlayerPrefs.SetInt(PlayerPrefabInfo.getEmailNum, getEmailNum);
        SetPhotoData();


    }

    public void CloseGetPhoto() {
        getPhoto.SetActive(false);
    }

    public void LediPlayAni() {
        ledi.transform.Find("101001000@skin").GetComponent<Animator>().Play("idell_p");
    }










}
